package com.lagou.filter;

import com.lagou.util.TraceIpUtil;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;

@Activate(group = {CommonConstants.PROVIDER, CommonConstants.CONSUMER})
public class TraceIpFilter implements Filter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {

        String traceIp = RpcContext.getContext().getAttachment("traceIp");

        if (StringUtils.isEmpty(traceIp)) {
            /**
             * 如果RpcContext未携带traceIp，从ThreadLocal中查询，并设置到RpcContext
             */
            traceIp = TraceIpUtil.getTraceIp();
            /**
             * 重新给RpcContext设置traceIp
             */
            RpcContext.getContext().setAttachment("traceIp", traceIp);
        } else {
            /**
             * 如果RpcContext携带了traceIp，将其设置到ThreadLocal
             */
            TraceIpUtil.setTraceIp(traceIp);
        }
        System.out.println("客户端ip为：" + traceIp);
        return invoker.invoke(invocation);
    }

}
